import { Injectable } from '@nestjs/common';
import Redis from 'ioredis';
import { redisConfig } from '../../redis.config';
@Injectable()
export class RedisService {
  private readonly redisClient: Redis;

  constructor() {
    this.redisClient = new Redis({
      ...redisConfig,
    });
  }

  setValue(key: string, value: string) {
    return this.redisClient.set(key, value);
  }
  // 带过期时间的set方法(单位：s)
  setWithExpiry(key: string, value: string, time: number = 4 * 60 * 60) {
    return this.redisClient.setex(key, time, value);
  }

  getValue(key: string) {
    return this.redisClient.get(key);
  }

  deleteKey(key: string) {
    return this.redisClient.del(key);
  }

  // 在哈希表（Hash）相关的方法中，field这是哈希表中的字段名称。
  //设置key中filed字段的数据value
  setHashField(key: string, field: string, value: string) {
    return this.redisClient.hset(key, field, value);
  }

  //获取key中的field字段数据
  getHashField(key: string, field: string) {
    return this.redisClient.hget(key, field);
  }

  //获取key中所有数据
  getAllHashFields(key: string) {
    return this.redisClient.hgetall(key);
  }
}
